package com.hangwei.aicabinet;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hangwei.aicabinet.adapter.OrderAdapter;
import com.hangwei.aicabinet.frament.SubOrderFragment;
import com.hangwei.aicabinet.model.bean.OrderBean;
import com.hangwei.aicabinet.model.entry.CloseAllDoor;
import com.hangwei.aicabinet.model.entry.ColseDoorFinish;
import com.hangwei.aicabinet.model.entry.ColseDoorUpdateFail;
import com.hangwei.aicabinet.model.entry.ErrorReturnEvent;
import com.hangwei.aicabinet.net.ViewCallBack;
import com.hangwei.aicabinet.presenter.MainPresenter;
import com.hangwei.aicabinet.util.LoadingDialog;
import com.hangwei.aicabinet.util.SPKey;
import com.hangwei.aicabinet.util.SPUtil;
import com.hangwei.aicabinet.util.ToastUtil;
import com.hangwei.aicabinet.view.MainView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * author: 张龙臣
 * date: 2018-08-27.
 */

public class MainActivity extends BaseActivity implements MainView, SwipeRefreshLayout.OnRefreshListener {

    private SubOrderFragment mFragment;
    private OrderAdapter mAdapter;
    private ArrayList<OrderBean> mData;
    private MainPresenter presenter;
    private SwipeRefreshLayout refreshLayout;

    public static String id = "";
    private boolean isCloseDoorRefresh = false;
    private Dialog dialog;
    private Dialog dialogErrorReturn;
    private AlertDialog mCountDownDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        App.isAdmin = false;
//        UpLoadUtil.init(this);
        EventBus.getDefault().register(this);
//        FrameLayout flContent = findViewById(R.id.flContent);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        ImageView ivRefresh = findViewById(R.id.ivRefresh);
        refreshLayout = findViewById(R.id.refreshLayout);
        LinearLayout llLogout = findViewById(R.id.llLogout);
        llLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });

        refreshLayout.setOnRefreshListener(this);

        mFragment = new SubOrderFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.flContent, mFragment).commit();

        mAdapter = new OrderAdapter(R.layout.item_order, null);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        presenter = new MainPresenter(this, refreshLayout, mAdapter);

        firstLoad();

        ivRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                firstLoad();
            }
        });
//        mFragment.setAddedLisenter(new SubOrderFragment.OnFragmentAddedLisenter() {
//            @Override
//            public void onFragmentAdded() {
//                mFragment.loadOrder(0);
//            }
//        });
//        showDialog();
//        showDialogFinish();
//        onColseDoorFinish(new ColseDoorFinish());
//        onCloseAllDoor(null);
//        onColseDoorUpdateFail(null);

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                presenter.loadMore();
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<OrderBean> data = mAdapter.getData();
                if (data.get(position).checked)  //如果点击的是被选中的item
                    return;
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).checked = i == position;
                    if (position == i) {
                        id = data.get(i).id;
                    }
                }
                mAdapter.notifyDataSetChanged();
//                Toast.makeText(getApplicationContext(), "点击：" + position, Toast.LENGTH_SHORT).show();
                mFragment.setData(data.get(position).entryList, data.get(position).ordernum);
            }
        });
    }

    private void firstLoad() {
        final Dialog dialog = LoadingDialog.showDialog(this, "加载中");
        presenter.refresh(new ViewCallBack() {
            @Override
            public void onNetworkStart() {
                dialog.show();
            }

            @Override
            public void onNetworkComplete(boolean isRight) {
                if (dialog.isShowing())
                    dialog.dismiss();
                refreshLayout.setRefreshing(false);
                if (isRight) {
                    List<OrderBean> data = mAdapter.getData();
                    if (data.size() == 0) {
                        mFragment.setEmptyView();
                    } else {
                        data.get(0).checked = true;
                        id = data.get(0).id;
                        mAdapter.notifyDataSetChanged();
                        mFragment.setData(data.get(0).entryList, data.get(0).ordernum);
                    }
                    if (isCloseDoorRefresh) {
                        isCloseDoorRefresh = false;
                        showDialogFinish();
                    }
                }
            }
        });
    }


    @Override
    public void onRefresh() {
        firstLoad();
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_check, null);
        TextView tvConfirm = inflate.findViewById(R.id.tvConfirm);
        TextView tvCancel = inflate.findViewById(R.id.tvCancel);
        TextView tvMsg = inflate.findViewById(R.id.tvMsg);
        TextView tvTitle = inflate.findViewById(R.id.tvTitle);
//        tvTitle.setText("提示");
        tvMsg.setText("是否确定退出登录？");
        tvCancel.setText("取消");
        tvConfirm.setText("确定");
        builder.setView(inflate);
        builder.setCancelable(true);
        final AlertDialog dialog = builder.create();
        dialog.show();
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                logout();
            }
        });
    }

    private void showDialogFinish() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_check_finish, null);
        TextView tvConfirm = inflate.findViewById(R.id.tvConfirm);
        TextView tvCancel = inflate.findViewById(R.id.tvCancel);
        TextView tvMsg = inflate.findViewById(R.id.tvMsg);
        TextView tvTitle = inflate.findViewById(R.id.tvTitle);
//        tvTitle.setText("提示");

        tvMsg.setText("10 秒后自动退出登录");

        tvCancel.setText("继续操作");
        tvConfirm.setText("退出登录");
        builder.setView(inflate);
        builder.setCancelable(true);
        mCountDownDialog = builder.create();
        mCountDownDialog.setCancelable(false);// 不可以用“返回键”取消
        mCountDownDialog.setCanceledOnTouchOutside(false);
        mCountDownDialog.show();
        countDown(tvMsg, mCountDownDialog);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCountDownDialog.dismiss();
                time = 10;
                handler.removeCallbacksAndMessages(null);
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handler.removeCallbacksAndMessages(null);
                mCountDownDialog.dismiss();
                logout();
            }
        });
    }

    int time = 10;
    Handler handler = new Handler();

    private void countDown(final TextView tvMsg, final AlertDialog dialog) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (time == 0) {
                    if (dialog != null && dialog.isShowing()) dialog.dismiss();
                    logout();
                } else {
                    time--;
                    tvMsg.setText(time + " 是否确定退出登录？");
                    countDown(tvMsg, dialog);
                }
            }
        }, 1000);
    }

    private void logout() {
        final Dialog dialog1 = LoadingDialog.showDialog(MainActivity.this, "退出登录中");
        presenter.logout(new ViewCallBack() {
            @Override
            public void onNetworkStart() {
                dialog1.show();
            }

            @Override
            public void onNetworkComplete(boolean isRight) {
                if (dialog1.isShowing())
                    dialog1.dismiss();
                handler.removeCallbacksAndMessages(null);
                if (isRight) {
                    SPUtil.setString(SPKey.Account.PERSON_ID, "");
                    ToastUtil.showToast("已退出登录");
                    Intent intent10 = new Intent(MainActivity.this, LoginActivity.class);
                    intent10.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent10);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onColseDoorFinish(ColseDoorFinish event) {
        isCloseDoorRefresh = true;
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
        firstLoad();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onColseDoorUpdateFail(ColseDoorUpdateFail event) {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCloseAllDoor(CloseAllDoor event) {
        if (dialogErrorReturn != null && dialogErrorReturn.isShowing())
            dialogErrorReturn.dismiss();
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_close_door, null);

        dialog = new Dialog(this, R.style.generic_dialog);
//        dialog.setContentView(inflate);
//        dialog.setCancelable(false);// 不可以用“返回键”取消
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(inflate, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

        dialog.show();

//        String type = SPUtil.getString(SPKey.CABINET_NUM);
//        if ("YD".equals(type.substring(3, 5))){
//            App.getmHandler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    if (dialog != null && dialog.isShowing())
//                        dialog.dismiss();
//                }
//            },10000);
//        }else if ("DG".equals(type.substring(3, 5))){
//            App.getmHandler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    if (dialog != null && dialog.isShowing())
//                        dialog.dismiss();
//                }
//            },3000);
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onErrorReturnEvent(ErrorReturnEvent event) {
        Log.i("onErrorReturnEvent--", event.msg);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_error_return, null);
        TextView tvConfirm = inflate.findViewById(R.id.tvConfirm);
        TextView tvMsg = inflate.findViewById(R.id.tvMsg);
        tvMsg.setText(event.msg);
        dialogErrorReturn = new Dialog(this, R.style.generic_dialog);
//        dialog.setContentView(inflate);
        dialogErrorReturn.setCancelable(false);// 不可以用“返回键”取消
        dialogErrorReturn.setCanceledOnTouchOutside(false);
        dialogErrorReturn.setContentView(inflate, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

        dialogErrorReturn.show();
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogErrorReturn.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (mCountDownDialog != null && mCountDownDialog.isShowing()) {
            handler.removeCallbacksAndMessages(null);
            mCountDownDialog.dismiss();
        }
        super.onDestroy();
//        SerialPortProxy.closeTabSerialPort();
//        SerialPortProxy.closeLockSerialPort();
        EventBus.getDefault().unregister(this);
    }
}
